package cn.buk.api.ctrip.service;


import cn.buk.common.JsonResult;
import com.ctrip.openapi.java.base.HttpAccessAdapter;
import com.ctrip.openapi.java.utils.GzipUtil;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;

/**
 * Created by william on 2015-2-15.
 */
public abstract class BaseCtripApiService {

    protected static final Logger logger = Logger.getLogger(BaseCtripApiService.class);

    /**
     * 0 - 不使用代理服务器
     * 1 - 使用代理服务器
     */
    protected int proxyUsed;
    protected String proxyHost;
    protected int proxyPort;

    protected BaseCtripApiService() {
    }

    protected String execApiRequest(String requestContent, String urlString, String paraName) {
        Proxy proxy = null;

        if (this.proxyUsed == 1){
            SocketAddress address = new InetSocketAddress(proxyHost, proxyPort);
            proxy = new Proxy(Proxy.Type.HTTP, address);
        }

        return HttpAccessAdapter.SendRequestToUrl(requestContent, urlString, paraName, proxy);
    }

    protected String execApiRequest2(final String requestContent, final String urlString, final String paraName) {
        Proxy proxy = null;

        if (this.proxyUsed == 1){
            SocketAddress address = new InetSocketAddress(proxyHost, proxyPort);
            proxy = new Proxy(Proxy.Type.HTTP, address);
        }

        String responseXml =  HttpAccessAdapter.SendRequestToUrl2(requestContent, urlString, paraName, proxy);

        byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(responseXml);
        bytes =GzipUtil.unGZip(bytes);
        try {
            responseXml = new String(bytes, "UTF8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return responseXml;
    }

    protected boolean isOverApiCallFrequency(String requestType) {
        //检查缓存，看看header节点中的API调用频率限制
        return false;

//        Element headerElement = (Element) cacheElement.getValue();
//
//        int accessCount = Integer.parseInt(headerElement.attributeValue("AccessCount"));
//        int currentCount = Integer.parseInt(headerElement.attributeValue("CurrentCount")) + 1;
//        logger.info(requestType + ": AccessCount=" + headerElement.attributeValue("AccessCount")
//                + ", CurrentCount=" + headerElement.attributeValue("CurrentCount")
//                + ", ResetTime=" + headerElement.attributeValue("ResetTime"));
//
//        return currentCount >= accessCount;
    }

    protected Document convertXml2Document(final String xml) {
        try {
            return new SAXReader().read(new StringReader(xml));
        } catch (DocumentException e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    protected Document convertXmlFile2Document(final String fileName) {
        File file = new File(fileName);
        if (!file.exists()) return null;

        try {
            return new SAXReader().read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 处理接口返回的XML内容的Header元素中的内容，判断接口运行是否成功
     * @param headerElement
     * @return
     */
    protected JsonResult processResponseElementHeader(final Element headerElement) {
        final String resultCode = headerElement.attributeValue("ResultCode");
        if ("Success".equalsIgnoreCase(resultCode)) {
            return JsonResult.createJsonResult(1);
        } else {
            final String resultMsg = headerElement.attributeValue("ResultMsg");
            logger.warn(resultMsg);
            return JsonResult.createJsonResult(-1, resultMsg);
        }
    }
}
